package org.jeecg.modules.carinfo.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.RestUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.carinfo.entity.CarRegister;
import org.jeecg.modules.carinfo.entity.RegisterDTO;
import org.jeecg.modules.carinfo.service.ICarRegisterService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 车辆登记
 * @Author: jeecg-boot
 * @Date: 2024-07-25
 * @Version: V1.0
 */
@Api(tags = "车辆登记")
@RestController
@RequestMapping("/carRegister/carRegister")
@Slf4j
public class RegisterController extends JeecgController<CarRegister, ICarRegisterService> {
    @Autowired
    private ICarRegisterService carRegisterService;

    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     *
     * @param carRegister carRegister
     * @param pageNo      pageNo
     * @param pageSize    pageSize
     * @param req         req
     * @return Result
     */
    @AutoLog(value = "车辆登记-分页列表查询")
    @ApiOperation(value = "车辆登记-分页列表查询", notes = "车辆登记-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CarRegister carRegister,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        queryWrapper.like("goods", "包装油").or().eq("goods", "包装辅材");
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "车辆登记-对外-分页列表查询")
    @ApiOperation(value = "车辆登记-对外-分页列表查询", notes = "车辆登记-对外-分页列表查询")
    @GetMapping(value = "/m/list")
    public Result<?> mQueryPageList(CarRegister carRegister,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest req) {
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        queryWrapper.like("goods", "包装油").or().eq("goods", "包装辅材");
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "车辆登记-审批列表")
    @ApiOperation(value = "车辆登记-审批列表", notes = "车辆登记-审批列表")
    @GetMapping(value = "/examineList")
    public Result<?> examineList(CarRegister carRegister,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        queryWrapper.like("goods", "包装油").or().eq("goods", "包装辅材");
        queryWrapper.ne("register_status", 1);
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param carRegister carRegister
     * @return Result
     */
    @AutoLog(value = "车辆登记-添加")
    @ApiOperation(value = "车辆登记-添加", notes = "车辆登记-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CarRegister carRegister) {
        carRegisterService.save(carRegister);
        return Result.OK("添加成功！");
    }

    /**
     * 外部-添加
     *
     * @param registerDTO carRegister
     * @return Result
     */
    @AutoLog(value = "车辆登记-外部-添加")
    @ApiOperation(value = "车辆登记-外部-添加", notes = "车辆登记-外部-添加")
    @PostMapping(value = "/m/addCarRegister")
    public Result<?> addCarRegister(@RequestBody RegisterDTO registerDTO) {
        CarRegister carRegister = new CarRegister();
        BeanUtils.copyProperties(registerDTO, carRegister);
        carRegister.setLocatin(registerDTO.getLocation());
        carRegister.setLisense(registerDTO.getLicense());
        carRegister.setStatus(registerDTO.getRegisterStatus());
        LambdaQueryWrapper<CarRegister> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CarRegister::getPlateNo, registerDTO.getPlateNo());
        wrapper.eq(CarRegister::getStatusLedger, 1);
        int count = carRegisterService.count(wrapper);
        if (count > 0) {
            carRegister.setStatusLedger(1);
        } else {
            carRegister.setStatusLedger(0);
        }
        carRegisterService.save(carRegister);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param carRegister carRegister
     * @return Result
     */
    @AutoLog(value = "车辆登记-编辑")
    @ApiOperation(value = "车辆登记-编辑", notes = "车辆登记-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CarRegister carRegister) {
        carRegisterService.updateById(carRegister);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id id
     * @return Result
     */
    @AutoLog(value = "车辆登记-通过id删除")
    @ApiOperation(value = "车辆登记-通过id删除", notes = "车辆登记-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        carRegisterService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids ids
     * @return Result
     */
    @AutoLog(value = "车辆登记-批量删除")
    @ApiOperation(value = "车辆登记-批量删除", notes = "车辆登记-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.carRegisterService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id id
     * @return Result
     */
    @AutoLog(value = "车辆登记-通过id查询")
    @ApiOperation(value = "车辆登记-通过id查询", notes = "车辆登记-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CarRegister carRegister = carRegisterService.getById(id);
        if (carRegister == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(carRegister);
    }

    /**
     * 导出excel
     *
     * @param request     request
     * @param carRegister carRegister
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CarRegister carRegister) {
        return super.exportXls(request, carRegister, CarRegister.class, "车辆登记");
    }

    @RequestMapping(value = "/oilExportXls")
    public ModelAndView oilExportXls(HttpServletRequest request, CarRegister carRegister) {
        // Step.1 组装查询条件
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, request.getParameterMap());
        queryWrapper.like("goods", "包装油").or().eq("goods", "包装辅材");
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<CarRegister> pageList = carRegisterService.list(queryWrapper);
        List<CarRegister> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "车辆登记"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, CarRegister.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams=new ExportParams("车辆登记报表", "导出人:" + sysUser.getRealname(), "车辆登记");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS,exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    private String getId(CarRegister item) {
        try {
            return PropertyUtils.getProperty(item, "id").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过excel导入数据
     *
     * @param request  request
     * @param response response
     * @return Result
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CarRegister.class);
    }

    @AutoLog(value = "车辆登记-分类统计")
    @ApiOperation(value = "车辆登记-分类统计", notes = "车辆登记-分类统计")
    @GetMapping(value = "/queryByCount")
    public Result<?> queryByCount() {
        //EnterpriseBasicInformation enterprise = enterpriseBasicInformationService.list().get(0);
        QueryWrapper<CarRegister> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("max(create_time) as create_time");
        Date max = carRegisterService.getOne(queryWrapper).getCreateTime();
        queryWrapper.clear();
        queryWrapper.select("min(create_time) as create_time");
        Date min = carRegisterService.getOne(queryWrapper).getCreateTime();
        long l = (max.getTime() - min.getTime()) / (3600 * 24 * 1000) + 1;
        queryWrapper.clear();
        queryWrapper.select("count(1) as count");
        Map<String, Object> map = carRegisterService.getMap(queryWrapper);
        long total = Long.valueOf(map.get("count").toString());
        long average = total / l;
        // 设置返回值
        List<Map<String, String>> list = carRegisterService.getCount();
        List<Map<String, String>> updatedList = new ArrayList<>();
        for (Map<String, String> mapString : list) {
            Map<String, String> updatedMap = new HashMap<>();
            String name = mapString.get("name");
            switch (name) {
                case "0":
                    updatedMap.put("name", "国零");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "1":
                    updatedMap.put("name", "国一");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "2":
                    updatedMap.put("name", "国二");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "3":
                    updatedMap.put("name", "国三");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "4":
                    updatedMap.put("name", "国四");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "5":
                    updatedMap.put("name", "国五");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "6":
                    updatedMap.put("name", "国六");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "D":
                    updatedMap.put("name", "新能源");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                default:
                    updatedMap.put("name", "排放标准未知");
                    updatedMap.put("value", mapString.get("value"));
            }
            updatedList.add(updatedMap);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", updatedList);
        jsonObject.put("total", total);
        jsonObject.put("average", average);
        return Result.OK(jsonObject);
    }

}
